package com.dsr.util;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.dsr.bean.SectionBean;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class BasicUtil {
    private static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
                 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

    public static String getToken(String claim) {
        String token = (String) getRequest().getAttribute("token");
        DecodedJWT decodedJWT = JwtUtil.getDecodedJWT(token);
        return decodedJWT.getClaim(claim).asString();
    }

    public static String getIp() {
        return getRequest().getRemoteAddr();
    }

    public static String getMD5(String passwd) {
        return DigestUtils.md5DigestAsHex(passwd.getBytes());
    }

    public static void setCookie(String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        getResponse().addCookie(cookie);
    }
    public static String getCode(){
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder();
        for(int i=0;i<6;i++){
            stringBuilder.append(codeSequence[random.nextInt(36)]);
        }
        return stringBuilder.toString();
    }

    public static Map<String ,Integer> getDays(){
        Calendar cal = Calendar.getInstance();
        DateFormat dateFormat = new SimpleDateFormat("MM-dd");
        Map<String,Integer> map =new TreeMap<>();
        for (int i = 0; i <7; i++) {
            cal.setTime(new Date());
            cal.add(Calendar.DATE, 0-i);
            String format = dateFormat.format(cal.getTime());
            map.put(format,0);
        }
        return map;
    }
    private static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    private static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
    }
}
